﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Things.OrderPlan;
using System.Data;
using Things.ThingsWeb;
using Things.Common;

namespace Things.Web.OrderPlan
{
    public partial class OrderPlanCart : PageUtility
    {
        /// <summary>
        /// 所有总价
        /// </summary>
        public double TotalPrice { get; set; }

        private Dictionary<Guid, Things.OrderPlan.Goods> _goods = new Dictionary<Guid, Things.OrderPlan.Goods>();
        protected void Page_Load(object sender, EventArgs e)
        {
            
                if (CurrentBuyer == null)
                {
                    Session[ConstantString.SessionSourceURL] = HttpContext.Current.Request.Url.PathAndQuery;
                    Response.Redirect("../Login.aspx");
                }

                this._ctlCart.DataSource = OrderPlanCartUtil.GetOrders(Context);
                this._ctlCart.DataBind();

                this.Panel1.Visible = this._ctlCart.Items.Count <= 0;

        }

        protected string GetGoodsName(string strGoodsId)
        {
            Things.OrderPlan.Goods goods = null;
            Guid goodsId = new Guid(strGoodsId);
            if (!_goods.ContainsKey(goodsId))
            {
                goods = new Things.OrderPlan.PlanningGoodsSearcher().Find(goodsId);
                _goods.Add(goodsId, goods);
            }
            else
            {
                goods = _goods[goodsId];
            }
            return goods.GoodsName;
        }

        protected string GetGoodsImageUrl(string strGoodsId)
        {
            Things.OrderPlan.Goods goods = null;
            Guid goodsId = new Guid(strGoodsId);
            if (!_goods.ContainsKey(goodsId))
            {
                goods = new Things.OrderPlan.PlanningGoodsSearcher().Find(goodsId);
                _goods.Add(goodsId, goods);
            }
            else
            {
                goods = _goods[goodsId];
            }
            return goods.GoodsImageURL;
        }

        protected string GetSetName(string strSetId)
        {
            Guid setId = new Guid(strSetId);
            Things.OrderPlan.Models.SaleSet saleSet = new SaleSetRepository().Find(setId);
            if (saleSet == null)
            {
                return "自选套餐";
            }
            return saleSet.Caption;
        }

        protected string GetUnitPrice(string strSetId, string strGoodsId)
        {
            Guid setId = new Guid(strSetId);
            Things.OrderPlan.Models.SaleSet saleSet = new SaleSetRepository().Find(setId);
            if (saleSet == null)
            {
                Guid goodsId = new Guid(strGoodsId);
                Things.OrderPlan.Models.SetParameter parameter = new Things.OrderPlan.SetParameterRepository().Find(goodsId);
                if (parameter != null)
                {
                    decimal a = Math.Round((parameter.P1 - ((parameter.N * parameter.P1 - parameter.PN) / (parameter.N - 1))), 2);
                    decimal b = Math.Round(((parameter.N * parameter.P1 - parameter.PN) / (parameter.N - 1)), 2);

                    DataTable table = this._ctlCart.DataSource as DataTable;
                    foreach (DataRow row in table.Rows)
                    {
                        if (new Guid((string)row["SetId"]) == setId)
                        {
                            int dCount = Convert.ToInt32(row["deliveredCount"]);
                            //int dCycle = Convert.ToInt32(row["deliveredCycle"]);
                            int dNumber = Convert.ToInt32(row["deliveredNumber"]);

                            decimal price=Math.Round(
                                dCount  * dNumber * a + b,
                                2);

                            // 商品超过N后,价格=Pn
                            return Math.Max(price, parameter.PN).ToString();
                        }
                    }
                }
            }
            return saleSet.UnitPrice.ToString();
        }

        protected string GetTotalPrice(string strSetId, string strGoodsId)
        {
            Guid setId = new Guid(strSetId);
            DataTable table = this._ctlCart.DataSource as DataTable;

            decimal totalPrice = 0;

            Things.OrderPlan.Models.SaleSet saleSet = new SaleSetRepository().Find(setId);
            if (saleSet != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    if (new Guid((string)row["SetId"]) == setId)
                    {
                        int dCount = Convert.ToInt32(row["deliveredCount"]);
                        int dCycle = Convert.ToInt32(row["deliveredCycle"]);
                        int dNumber = Convert.ToInt32(row["deliveredNumber"]);

                        if (decimal.TryParse((dCount * dNumber * saleSet.UnitPrice).ToString(), out totalPrice))
                        {
                            
                        }
                        else
                        {
                            totalPrice = 0;
                        }

                    }
                }
            }
            else
            {
                Guid goodsId = new Guid(strGoodsId);
                Things.OrderPlan.Models.SetParameter parameter = new Things.OrderPlan.SetParameterRepository().Find(goodsId);
                if (parameter != null)
                {
                    decimal a = Math.Round((parameter.P1 - ((parameter.N * parameter.P1 - parameter.PN) / (parameter.N - 1))), 2);
                    decimal b = Math.Round(((parameter.N * parameter.P1 - parameter.PN) / (parameter.N - 1)), 2);

                    foreach (DataRow row in table.Rows)
                    {
                        if (new Guid((string)row["SetId"]) == setId)
                        {
                            int dCount = Convert.ToInt32(row["deliveredCount"]);
                            //int dCycle = Convert.ToInt32(row["deliveredCycle"]);
                            int dNumber = Convert.ToInt32(row["deliveredNumber"]);

                            decimal price = Math.Round(dCount * dNumber * a + b, 2);
                            totalPrice = Math.Round(Math.Max(price, parameter.PN) * dCount * dNumber, 2);
                            
                            
                            break;
                        }
                    }
                }
            }

            lblCount.Text = Math.Round(totalPrice, 2).ToString();
            decimal yunFei = 0;
            if (totalPrice <= ConfigureValue.DingGouMianYunFei)
            {
                yunFei = Math.Round(ConfigureValue.YunFei);
            }
            lblYunFei.Text = yunFei.ToString();

            decimal dingDanJinE = Math.Round(totalPrice + yunFei, 2);
            lblDingDanJinE.Text = dingDanJinE.ToString();
            
            return totalPrice.ToString();
        }

    

        protected void _ctlCart_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                DataTable dt = _ctlCart.DataSource as DataTable;
                DataRow row = dt.Rows[e.Item.ItemIndex];
                Guid setId = new Guid((string)row["SetId"]);
                OrderPlanCartUtil.Remove(this.Context, setId, "~/OrderPlan/OrderPlanCart.aspx");
            }
        }

        protected void LinkButton1_Click(object sender, ImageClickEventArgs e)
        {
            // 收货地址
            string buyerAddress = string.Empty;
            HiddenField hfAddress = (HiddenField)this.BuyerAddress1.FindControl("hfAddress");
            if (hfAddress != null && string.IsNullOrEmpty(hfAddress.Value.Trim()) == false)
            {
                buyerAddress = hfAddress.Value.Trim();
            }

            // 发票信息
            string faPiaoXinXi = rblFaPiaoLeiXing.SelectedValue + ", " + txtFaPiaoTaiTou.Text.Trim() + ", " + txtFaPiaoNeiRong.Text.Trim();

           

            // 订购信息
            string strSetID = "";
            string strGoodsID = "";
            int deliveredCount = 0;
            int deliveredCycle = 0;
            int deliveredNumber = 0;
            DataTable table = this._ctlCart.DataSource as DataTable;
            if (table != null)
            {
                DataRowCollection rows = table.Rows;
                if (rows.Count > 0)
                {
                    strSetID = rows[0]["SetId"].ToString();
                    strGoodsID = rows[0]["GoodsId"].ToString();

                    int.TryParse(rows[0]["deliveredCount"].ToString(), out deliveredCount);
                    int.TryParse(rows[0]["deliveredCycle"].ToString(), out deliveredCycle);
                    int.TryParse(rows[0]["deliveredNumber"].ToString(), out deliveredNumber);
                }
            }
            // SaleSet
            Guid setId = new Guid(strSetID);
            Things.OrderPlan.Models.SaleSet saleSet = new SaleSetRepository().Find(setId);

            double totalPrice = 0;
            if (double.TryParse(lblDingDanJinE.Text, out totalPrice) == true
                && string.IsNullOrEmpty(buyerAddress)==false)
            {
                if (totalPrice >0)
                {
                   
                    OrderPlanRepository rep = new OrderPlanRepository();
                    Things.OrderPlan.Models.OrderPlan opModel = new Things.OrderPlan.Models.OrderPlan();
                    opModel.BuyerAddress = buyerAddress;
                    opModel.BuyerName = "";
                    opModel.BuyerPhone = "";
                    opModel.CreatedDate = DateTime.Now;
                    opModel.DeliveredCount = deliveredCount;
                    opModel.DeliveredCycle = deliveredCycle;
                    opModel.DeliveredNumber = deliveredNumber;
                    opModel.FaPiaoXinXi = faPiaoXinXi;
                    opModel.Id = Guid.NewGuid();
                    opModel.IsPaid = true;
                    opModel.GoodsId = new Guid(strGoodsID);
                    opModel.TotalPrice = Math.Round(totalPrice, 2);
                    opModel.UnitPrice = Math.Round(totalPrice, 2); ;
                    opModel.UserName = CurrentBuyer.Account;
                    opModel.SaleSetId = setId;
                    opModel.Status = ConstantString.GoodsOrderSatus.未付款.ToString();


                    if (new OrderPlanRepository().Restore(opModel))
                    {
                        // 付款
                        Things.OrderPlan.Models.OrderPlan model = rep.Find(opModel.Id);
                        if (model != null)
                        {
                            string url = HttpContext.Current.Request.Url.AbsoluteUri;
                            // http://localhost:1302/TESTERS/Default6.aspx

                            string path = HttpContext.Current.Request.Url.AbsolutePath;
                            // /TESTERS/Default6.aspx

                            string hostURL = url.Remove(url.IndexOf(path), path.Length);

                            Pay(model.OrderPlanNumber.ToString(),
                                Math.Round(model.TotalPrice, 2).ToString(),
                                "goodsName",
                                "",
                                "",
                                hostURL + "/OrderPlan/Callback.aspx",
                                "");
                        }
                    }
                    else
                    {
                    }
                }
            }
        }
    }
}